import inquirer from 'inquirer';
import chalk from 'chalk';
import { Logger } from '../utils/logger.js';

export async function configMenu(configManager) {
  let shouldExit = false;

  while (!shouldExit) {
    Logger.separator();

    const configs = configManager.listConfigs();
    const configNames = Object.keys(configs);

    const { action } = await inquirer.prompt([
      {
        type: 'list',
        name: 'action',
        message: '配置管理',
        choices: [
          {
            name: '📋 查看所有配置',
            value: 'list',
            disabled: configNames.length === 0,
          },
          {
            name: '👁️  查看配置详情',
            value: 'view',
            disabled: configNames.length === 0,
          },
          {
            name: '🗑️  删除配置',
            value: 'delete',
            disabled: configNames.length === 0,
          },
          new inquirer.Separator(),
          {
            name: '⬅️  返回主菜单',
            value: 'back',
          },
        ],
      },
    ]);

    try {
      switch (action) {
        case 'list':
          listConfigs(configManager);
          break;
        case 'view':
          await viewConfig(configManager);
          break;
        case 'delete':
          await deleteConfig(configManager);
          break;
        case 'back':
          shouldExit = true;
          break;
      }
    } catch (error) {
      Logger.error(error.message);
    }
  }
}

function listConfigs(configManager) {
  Logger.separator();
  const configs = configManager.listConfigs();

  if (Object.keys(configs).length === 0) {
    Logger.warn('没有保存的配置');
    return;
  }

  const tableData = Object.entries(configs).map(([name, config]) => ({
    名称: chalk.cyan(name),
    主机: config.host,
    端口: config.port,
    用户: config.username,
    认证: config.authType === 'password' ? '密码' : '私钥',
    创建时间: new Date(config.createdAt).toLocaleString(),
  }));

  console.table(tableData);
  Logger.separator();
}

async function viewConfig(configManager) {
  Logger.separator();
  const configs = configManager.listConfigs();
  const configNames = Object.keys(configs);

  const { configName } = await inquirer.prompt([
    {
      type: 'list',
      name: 'configName',
      message: '选择配置',
      choices: configNames,
    },
  ]);

  const config = configs[configName];

  console.log(chalk.cyan(`\n配置: ${configName}`));
  console.log(chalk.gray('─'.repeat(50)));
  console.log(`主机: ${config.host}`);
  console.log(`端口: ${config.port}`);
  console.log(`用户名: ${config.username}`);
  console.log(`认证方式: ${config.authType === 'password' ? '密码' : '私钥'}`);

  if (config.authType === 'key') {
    console.log(`私钥路径: ${config.privateKeyPath}`);
    if (config.passphrase) {
      console.log(`密码短语: ****`);
    }
  } else {
    console.log(`密码: ${'*'.repeat(8)}`);
  }

  console.log(`创建时间: ${new Date(config.createdAt).toLocaleString()}`);
  console.log(`更新时间: ${new Date(config.updatedAt).toLocaleString()}`);
  console.log(chalk.gray('─'.repeat(50)));
}

async function deleteConfig(configManager) {
  Logger.separator();
  const configs = configManager.listConfigs();
  const configNames = Object.keys(configs);

  const { configName } = await inquirer.prompt([
    {
      type: 'list',
      name: 'configName',
      message: '选择要删除的配置',
      choices: configNames,
    },
  ]);

  const { confirm } = await inquirer.prompt([
    {
      type: 'confirm',
      name: 'confirm',
      message: `确定要删除配置 "${configName}" 吗?`,
      default: false,
    },
  ]);

  if (confirm) {
    configManager.deleteConfig(configName);
    Logger.success(`配置 "${configName}" 已删除`);
  } else {
    Logger.warn('操作已取消');
  }
  Logger.separator();
}
